import { isEmpty, reverse } from "lodash";
import { getServerConfig } from "../libs/utils";
import { login } from "../services/session";
import { send_origin_request } from "../libs/request";
// 登录
const handleLogin = async (ctx: any) => {
  const params = ctx.request.body;

  let referer = ctx.cookies.get("referer");
  referer = referer ? decodeURIComponent(referer) : "";

  const error = {};
  let user: any = null;

  if (
    isEmpty(params) ||
    !params.username ||
    !params.password ||
    !params.captcha
  ) {
    Object.assign(error, {
      status: 400,
      reason: ctx.t("无效的登录参数"),
      message: ctx.t("无效的登录参数"),
    });
  }

  if (isEmpty(error)) {
    try {
      // params.password = decryptPassword(params.encrypt, 'kubesphere')
      // 判断验证码
      if (ctx.session.captcha) {
        if (params.captcha.toLowerCase() != ctx.session.captcha.toLowerCase()) {
          Object.assign(error, {
            status: 400,
            reason: ctx.t("验证码"),
            message: ctx.t("验证码输入错误"),
          });
          ctx.body = error;
          return;
        }
      } else {
        Object.assign(error, {
          status: 400,
          reason: ctx.t("验证码"),
          message: ctx.t("验证码过期，请刷新验证码"),
        });
        ctx.body = error;
        return;
      }

      const pw = Buffer.from(
        Buffer.from(params.password, "base64").toString("utf8"),
        "base64"
      ).toString("utf8");
      const tpw = reverse(pw.split("")).join("");
      // 判断是否有skd
      if (tpw.indexOf("skd") == -1) {
        Object.assign(error, {
          status: 400,
          reason: ctx.t("错误"),
          message: ctx.t("用户名或密码错误"),
        });
        ctx.body = error;
        return;
      }
      user = await login(
        {
          username: params.username,
          password: tpw.slice(0, tpw.length - 3),
        },
        ctx.request.header
      );
      if (!user) {
        Object.assign(error, {
          status: 400,
          reason: ctx.t("错误"),
          message: ctx.t("用户名或密码错误"),
        });
      }
    } catch (err: any) {
      ctx.app.emit("error", err);

      switch (err.code) {
        case 401:
          Object.assign(error, {
            status: err.code,
            reason: ctx.t("错误"),
            message: ctx.t("用户名或密码错误"),
          });
          break;
        case 429:
          Object.assign(error, {
            status: err.code,
            reason: ctx.t("请求次数过多"),
            message: ctx.t("请求次数过多，请稍后重试"),
          });
          break;
        case 502:
          Object.assign(error, {
            status: err.code,
            reason: ctx.t("错误"),
            message: ctx.t("服务器内部错误"),
          });
          break;
        case "ETIMEDOUT":
          Object.assign(error, {
            status: 400,
            reason: ctx.t("错误"),
            message: ctx.t("服务器内部错误"),
          });
          break;
        default:
          Object.assign(error, {
            status: err.code,
            reason: err.statusText,
            message: err.message,
          });
      }
    }
  }

  if (!isEmpty(error) || !user) {
    ctx.body = error;
    return;
  }
  ctx.cookies.set("token", user.token);
  ctx.cookies.set("username", user.username);
  ctx.cookies.set("expires", user.expires);
  // todo 设置角色
  ctx.cookies.set("referer", null);
  ctx.session.userinfo = user;
  ctx.body = {
    status: 200,
    reason: "success",
    userinfo: user,
    message: ctx.t("登录成功"),
  };
};

const handleLogout = (ctx: any) => {
  ctx.cookies.set("token", null);
  ctx.cookies.set("expires", null);
  ctx.cookies.set("referer", null);
  ctx.session.userinfo = null;
  ctx.redirect("/");
};

export { handleLogin, handleLogout };
